/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj, getNowFormatStr,getMpListShort } from '@/utils/util'
import {sinceCount} from '@/utils/util'
import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import {generatorStockTake,batchCounterAuditStatus,getMaterialByBarCode,addPrintHistory} from '@/api/api'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { mixinDevice } from '@/utils/mixin.js'
import { getLanCode } from '@/lang'
import { titleObj } from '../lang/category'
import moment from 'moment';
import {getFileNameByKey} from '@/utils/print/menuPrint.js';
import ColumnsSetting from '@/views/bill/modules/ColumnsSetting';

import { queryMaterialCategoryTreeList} from '@/api/api'
// 导出用
import { openDownloadDialog, sheet2blob} from "@/utils/util"
export const JeecgListMixin = {
  mixins: [mixinDevice],
  components: {
    ColumnsSetting
  },
  data () {
    return {
      //token header
      tokenHeader: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
      /*卡片样式 */
      cardStyle: '',
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 商品分类 */
      categoryTree:[],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          let lanCode = getLanCode()
          if (lanCode === 'zh') {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          } else {
            return range[0] + '-' + range[1] + ' Common ' + total + ' Strip'
          }
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 控制table高度 */
      scroll: {},
      /* 排序参数 */ 
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      fileList: [],
      setChildArr: [],
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中keys1*/
      selectedRowKeys1: [],
      /* table选中keys2*/
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows: [],
      /* table选中records1*/
      selectionRows1: [],
      /* table选中records2*/
      selectionRows2: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      /** 是否加载时就执行 */
      disableMixinCreated: false,
      /* 按钮权限 */
      btnEnableList: '',
      /* 导出按钮loading */
      downLoading:false,
      printDirectiveData:{
        printType:1,//不走打印次数权限
      },//权限打印参数
      dateFormat: 'YYYY-MM-DD',
      currentDay: moment().format('YYYY-MM-DD'),
    }
  },
  created () {
    //list查询默认筛选今天
    if(process.env.NODE_ENV == "production"){
      let dateString = [moment(this.currentDay, this.dateFormat), moment(this.currentDay, this.dateFormat)]
      this.$set(this.queryParam,'createTimeRange',dateString)
      this.queryParam.beginTime = this.currentDay
      this.queryParam.endTime = this.currentDay
    }
    if (this.isDesktop()) {
      this.cardStyle = 'height:' + (document.documentElement.clientHeight - 125) + 'px'
    }
    if (!this.disableMixinCreated) {
      console.log(' -- mixin created -- ')
      this.loadData()
      //初始化字典配置 在自己页面定义
      this.initDictConfig()
      //初始化按钮权限
      this.initActiveBtnStr()
    }
  },
  mounted () {
    this.initScroll()
  },
  methods: {
    moment,sinceCount,
    loadData (arg) {
      console.log(this.url.list, this.title, 'handler: loadData')
      if (!this.url.list) {
        this.$message.error(this.$t('popup.pleaseProperty'))
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      
      this.queryParam.r_loginName = this.getLocalStorage('pro__Login_Userinfo').loginName
      this.queryParam.r_userName = this.getLocalStorage('pro__Login_Userinfo').username
      this.queryParam.r_title = this.$route.meta.title
      var params = this.getQueryParams() //查询条件
      // 康虎云报表打印多传参数
      this.loading = true
      getAction(this.url.list, params).then(res => {
        if (res.code === 200) {
          this.dataSource = res.data.rows
          this.ipagination.total = res.data.total
          this.tableAddTotalRow(this.columns, this.dataSource)
        }
        if (res.code === 510) {
          this.$message.warning(res.data)
        }
        this.loading = false
      })
    },
    
    getLocalStorage (key) {
      var value = localStorage.getItem(key) // 取回 value 变量
      this.localStorageKeyJson = JSON.parse(value)
      return this.localStorageKeyJson.value
    },
    loadAllData (arg) {
      return new Promise((resolve, reject) => {
        if (!this.url.list) {
          this.$message.error(this.$t('popup.pleaseProperty'))
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        var params = this.getQueryParams() //查询条件
        params.pageSize = this.ipagination.total
        getAction(this.url.list, params).then(res => {
          if (res.code === 200) {
            let dataSource = res.data.rows
            this.tableAddTotalRow(this.columns,dataSource)
            resolve(dataSource)
          }
          if (res.code === 510) {
            this.$message.warning(res.data)
            reject()
          }
        })
      })
    },
    initDictConfig () {
      //console.log("--这是一个假的方法!")
    },
    columnsChange(checkedValues,defColumns){
      this.columns = defColumns.filter(item => {
          if (checkedValues.includes(item.dataIndex)) {
          return true
          }
          return false
      })
    },
    handleSuperQuery (params, matchType) {
      //高级查询方法
      if (!params) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.loadData(1)
    },
    getQueryParams () {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      let searchObj = {}
      searchObj.search = JSON.stringify(this.queryParam)
      var param = Object.assign(sqp, searchObj, this.isorter, this.filters)
      param.field = this.getQueryField()
      // param.promotionType = this.promotionType
      param.currentPage = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField () {
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    
    /**
     * 
     * @param {string} name 模板名称，如果是列表的详情就需要传，因为无法通过路由获取
     */
    async generatePrintData(event,name){
      const Cols = this.columns.map(v=>{
        let item ={
          name: v.dataIndex,
          required: false,
          size: 255,
          type: "str",
          // key:v.dataIndex
        }
        return item
      })
      const data = this.dataSource.map(v=>{
        let item ={}
        this.columns.forEach(val=>{
          item[val.dataIndex] = v[val.dataIndex]
        })
        return item ;
      })
      // 表体数据
      let table = {
        Tables:[]
      }
      table.Tables[0] = {
        Cols:Cols,
        Data:data,
        Name:'table'
      }
      // 表头数据
      let ColHead = []

      for (let key in this.queryParam) {
        ColHead.push({
          name: key,
          required: false,
          size: 255,
          type: "str",
        })
      }
      table.Tables[1] = {
        Cols:ColHead,
        Data:[this.queryParam],
        Name:'headerInfo'
      }
      table.ver=4,
      table.Copies=1,
      table.printer="pdfFactory Pro",
      table.preview=0,
      table.taskid="1234567890",
      table.upload_templ_url="http://192.168.147.1:8081",
      table.upload_templ_user="myname",
      table.upload_templ_password="1234567",
      table.upload_templ_comment = this.$route.name
      table.upload_templ_name = this.$route.name
      const templateFileName = name || getFileNameByKey(this.$route.name,getLanCode() === 'en' ? 'en' : 'text' )
      table.template = `${templateFileName}.fr3`
      console.log('table :>> ', table);
      const Print = require('@/utils/print/cfprint_ext')
      Print.sendMsg(table)
    },
    
    // 列表导出
    async exportExcel(event,name) {
      let aoa = [this.columns.map(v=>v.title)]
      this.downLoading = true
      // 获取要导出的数据
      let dataSource = await this.loadAllData(1)
      this.downLoading = false
      for (let i = 0; i < dataSource.length; i++) {
        let item = []
        for (let l = 0; l < this.columns.length; l++) {
          let column = this.columns[l]
          let text = dataSource[i][column.dataIndex] == 0 ? 0 : (dataSource[i][column.dataIndex] || '')
            // 有自定义方法
            if(typeof(column.customRender) ==="function"){
              let res = column.customRender(text,dataSource[i],i)
              // 返回的是node节点
              if(res && typeof(res.componentOptions)!="undefined"){
                text = res.componentOptions.children[0].text
              }else{
                text = res == 0 ? 0 : (res || '') 
              }
            }
            item.push(text)
        }
        aoa.push(item)
      }
      let header = `${this.$route.name} - ${this.getLocalStorage('pro__Login_Userinfo').loginName}     ${this.queryParam.beginTime || (this.queryParam.search && this.queryParam.search.beginTime) || ''} ~ ${this.queryParam.endTime || (this.queryParam.search && this.queryParam.search.endTime) || ''}`
      aoa.unshift([header])
      openDownloadDialog(sheet2blob(aoa,name || this.$route.name,this.columns), name || this.$route.name)
    },
    
    onSelect2 (record, selected) {
      let param = {
        headerId: record.id,
        mpList: '',
        linkType: ''
      }
      this.selectedRowKeys2 = [record.id]
      this.childLoading = true;
      getAction(this.url.detailList, param).then(res => {
        this.childLoading = false;
        if (res && res.code === 200) {
          let dataSource1 = res.data.rows
          // 过滤finishNumber
          this.dataSource1 = dataSource1.filter(v=>v.finishNumber < v.basicNumber)
          this.setChildArr = this.dataSource1
          // 若选中，直接push
          if (selected) {
            this.selectionRows2 = this.setChildArr
            this.setChildArr.forEach(item => {
              this.selectionRows1.push(item)
              this.selectedRowKeys1.push(item.id)
            })
          } else {
            // 若取消选中，则查找到这条数据删除
            let index = this.selectionRows2.findIndex(item => item.id == record.id)
            if (index >= 0) {
              this.selectionRows2.splice(index, 1)
            }
            this.setChildArr.forEach(item => {
              let index1 = this.selectionRows1.findIndex(item1 => item1.id == item1.id)
              let index2 = this.selectedRowKeys1.findIndex(item2 => item2 == item.id)
              if (index1 >= 0) {
                this.selectionRows1.splice(index1, 1)
              }
              if (index2 >= 0) {
                this.selectedRowKeys1.splice(index2, 1)
              }
            })
          }
          // findStockByDepotAndBarCode
          let materialIds = this.selectionRows2.map(v=>v.materialId)
          // 重新获取配送仓库的库存
          let param = {
            // barCode: barCodes,
            depotId: record.anotherDepotId,
            mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
            materialId: materialIds.join(','),
          }
          getMaterialByBarCode(param).then(result=>{
            let stockArr = result.data
            this.selectionRows2.map(v=>{
              let item = stockArr.find(val=>val.id === v.materialId)
              if(item){
                v.stock = item.stock
                v.linkId = v.id
              }
              return v
            })
            console.log('selectionRows2 :>> ', this.selectionRows2);
          })
        }
      }).catch(e=>{
      this.childLoading = false;
      })
    },
    onSelectAll2 (selected, selectedRows, changeRows) {
      // 若选中，直接push
      if (selected) {
        // 单选中部分几条数据，此时点击全选，将 changeRows 剩下的几条为选中数据选中
        // this.selectedRowKeys = this.selectedRowKeys.concat(changeRows)
        this.selectedRowKeys2 = []
        this.$message.warning('不支持全选')
      } else {
        // 若取消选中，则为空
        this.selectedRowKeys2 = []
        this.selectedRowKeys1 = []
      }
    },
    onSelectChange2 (selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      // this.selectionRows = selectionRows
    },

    onSelect1 (record, selected) {
      // 若选中，直接push
      console.log('777 :>> ', 777);
      if (selected) {
        this.selectionRows1.push(record)
        this.selectedRowKeys2 = [record.headerId]
        this.selectionRows2 = [record]
      } else {
        // 若取消选中，则查找到这条数据删除
        let index1 = this.selectionRows1.findIndex(item1 => item1.id == record.id)
        if (index1 >= 0) {
          this.selectionRows1.splice(index1, 1)
          this.selectedRowKeys2 = []
        }
      }
    },
    onSelectAll1 (selected, selectedRows, changeRows) {
      
      this.selectedRowKeys2 = selectedRows.map(v=>v.headerId)
      this.selectionRows2 = selectedRows
    },
    onSelectChange1 (selectedRowKeys, selectionRows) {
      this.selectedRowKeys1 = selectedRowKeys
      // this.selectionRows1 = selectionRows
    },

    // 原始
    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected () {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    searchQuery () {
      this.loadData(1)
    },
    superQuery () {
      this.$refs.superQueryModal.show()
    },
    searchReset () {
      this.queryParam = {}
      this.loadData(1)
    },
    batchSetStatus: function (status) {
      if (!this.url.batchSetStatusUrl) {
        this.$message.error(this.$t('popup.pleaseUrlBatch'))
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning(this.$t('otherJS.checkPieceOfData'))
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: this.$t('commodityManagement.confirmOperation'),
          content: this.$t('commodityManagement.operateSelected'),
          onOk: function () {
            that.loading = true
            postAction(that.url.batchSetStatusUrl, { status: status, ids: ids })
              .then(res => {
                if (res.code === 200) {
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.data.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          }
        })
      }
    },
    batchDel: function () {
      try {
        if (this.$route.name !== '商品信息' || this.$route.name!=='Commodity information') {
          this.selectionRows.forEach(item => {
            if (item.status !== '0') {
              this.$message.warning(this.$t('commodityManagement.sorryUnreviewedCannotDel'))
              throw new Error(this.$t('commodityManagement.sorryUnreviewedCannotDel'))
            }
          })
        }
      } catch (e) {
        if (e.message === this.$t('commodityManagement.sorryUnreviewedCannotDel')) throw e
      }
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning(this.$t('otherJS.checkPieceOfData'))
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: this.$t('commodityManagement.confirmDeletion'),
          content: this.$t('commodityManagement.whetherDelCheckedData'),
          onOk: function () {
            that.loading = true
            deleteAction(that.url.deleteBatch, { ids: ids })
              .then(res => {
                if (res.code === 200) {
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.data.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          }
        })
      }
    },
    showMaterialInOutList: function () {
      if (!this.url.add) {
        this.$message.error('请设置url.add属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning(this.$t('otherJS.checkPieceOfData'))
        return
      } else {
        var ids = []
        this.selectionRows.forEach(item => {
          ids.push({
            id: item.mid,
            depotId: item.depotId
          })
        })
        ids = JSON.stringify(ids)
        // ids = ids.toString()
        // for (var a = 0; a < this.selectedRowKeys.length; a++) {
        //   ids += this.selectedRowKeys[a] + ','
        // }
        let params = {
          // ids: ids,
          replenishment: ids,
          passDirect: true,
          functionId: this.$route.meta.id
        }
        var that = this
        this.$confirm({
          title: this.$t('commodityManagement.confirmAddGoods'),
          content: this.$t('commodityManagement.whetherAddGoods'),
          onOk: function () {
            that.loading = true
            postAction(that.url.add, params)
              .then(res => {
                if (res.code === 200) {
                  that.loadData()
                  that.onClearSelected()
                  that.$message.success(res.msg)
                } else {
                  that.$message.warning(res.data.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          }
        })
      }
    },
    myHandleReverseAudit(record){
      if(record.status === '0') {
        this.$message.error(this.$t('popup.sorryReverseAudit'))
        return;
      }
      let params={
        ids:record.id
      }
      this.$set(record,'reverseloading'.true)
      postAction(this.url.deApprovalUrl,params).then(res=>{
        this.$set(record,'reverseloading'.false)
        if(res.code == 200){
          this.$message.success(this.$t('systemManagement.operation')+this.$t('systemManagement.success'))
          this.loadData()
        }else{
          this.$message.error(res.data.message)
        }
      })
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      that.loading = true
      deleteAction(that.url.delete, { id: id }).then(res => {
        if (res.code === 200) {
          that.loading = false
          that.loadData()
        } else {
          that.$message.warning(res.data.message)
        }
      })
    },
    handleEdit: function (record) {
      console.log(999);
      
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = this.$route.name + '-' + this.$t('defaultTranslate.edit')
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function () {
      console.log('handler: handleAdd, title: '+ this.$route.name)
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = this.$route.name + '-' + this.$t('setailManagement.newlyAdded')
      this.$refs.modalForm.disableSubmit = false
    },
    handleReleasePurchaseAdd: function () {
      if (this.selectionRows.length == 1) {
        if (this.selectionRows[0].purchaseStatus == '2') {
          this.$message.warning(this.$t('commodityManagement.operatorBillHasCompleted'))
          return
        }
        this.$refs.releaseModalForm.add()
        this.$refs.releaseModalForm.release(this.selectionRows[0])
        this.$refs.releaseModalForm.title = '下达采购订单列表'
        this.$refs.releaseModalForm.disableSubmit = false
      } else if (this.selectionRows.length == 0) {
        this.$message.warning(this.$t('otherJS.checkPieceOfData'))
      } else if (this.selectionRows.length > 1) {
        this.$message.warning('只能勾选一条数据')
      }
    },
    myHandleStock: function () {
      if (this.selectionRows.length == 1) {
        if (this.selectionRows[0].purchaseStatus == '2') {
          this.$message.warning('此数据已完成盘点')
          return
        }
        // 处理
        let params = {
          id:this.selectionRows[0].id,
          passDirect:true
        }
        this.$confirm({
          content: this.$t('reportQuery.isInventory'),
          onOk: () => {
            this.stockLoading = true;
            generatorStockTake(params).then(res=>{
              if(res.code === 200){
                this.$message.success(this.$t('systemManagement.success'))
                this.loadData()
              }else{
                this.$message.error(res.data.message)
              }
            this.stockLoading = false;

            })
          }
        })
        
      } else if (this.selectionRows.length == 0) {
        this.$message.warning(this.$t('otherJS.checkPieceOfData'))
      } else if (this.selectionRows.length > 1) {
        this.$message.warning('只能勾选一条数据')
      }
    },
    handleTableChange (pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      if (pagination && pagination.current) {
        this.ipagination = pagination
      }
      this.loadData()
    },
    handleToggleSearch () {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
    getPopupField (fields) {
      return fields.split(',')[0]
    },
    modalFormOk () {
      console.log('modalFormOk')
      // 新增/修改 成功时，重载列表
      this.loadData()
    },
    handleDetail: function (record, type) {
      this.$refs.modalDetail.show(record, type)
      if(getLanCode() === 'en'){
        type = titleObj[type] || type
      }
      this.$refs.modalDetail.title = type
    },
    /* 导出 */
    handleExportXls2 () {
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()))
      let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`
      window.location.href = url
    },
    handleExportXls (fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '_' + getNowFormatStr() + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel (info) {
      this.loading = true
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200) {
            this.$message.success(info.file.response.data || `${info.file.name} 文件上传成功`)
          } else {
            this.$message.warning(info.file.response.data)
          }
          this.loadData()
          this.loading = false
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
          this.loading = false
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
        this.loading = false
      }
    },
    /* 图片预览 */
    getImgView (text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    /* 文件下载 */
    uploadFile (text) {
      if (!text) {
        this.$message.warning('未知的文件')
        return
      }
      if (text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      let url = getFileAccessHttpUrl(text)
      window.open(url)
    },
    /* 按钮权限 */
    initActiveBtnStr () {
      let btnStrList = Vue.ls.get('winBtnStrList') //按钮功能列表 JSON字符串
      this.btnEnableList = '' //按钮列表
      let pathName = location.pathname
      if (pathName.indexOf('/plugins') > -1) {
        pathName = '/system' + pathName
      }
      if (pathName && btnStrList) {
        for (let i = 0; i < btnStrList.length; i++) {
          if (btnStrList[i].url === pathName) {
            if (btnStrList[i].btnStr) {
              this.btnEnableList = btnStrList[i].btnStr
            }
          }
        }
      }
    },
    /* 初始化表格横向或纵向滚动 */
    initScroll () {
      if (this.isMobile()) {
        this.scroll.y = ''
      } else {
        let basicLength = 274
        let searchWrapperDomLen = 0,
          operatorDomLen = 0
        //搜索区域
        let searchWrapperDom = document.getElementsByClassName('table-page-search-wrapper')
        //操作按钮区域
        let operatorDom = document.getElementsByClassName('table-operator')
        if (searchWrapperDom && searchWrapperDom[0]) {
          searchWrapperDomLen = searchWrapperDom[0].offsetHeight
        }
        if (operatorDom && operatorDom[0]) {
          operatorDomLen = operatorDom[0].offsetHeight + 10
        }
        this.scroll.x = 1640
        this.scroll.y = document.documentElement.clientHeight - searchWrapperDomLen - operatorDomLen - basicLength
      }
    },
    /** 表格增加合计行 */
    tableAddTotalRow (columns, dataSource) {
        //分页条数为11、21、31等的时候增加合计行
        let numKey = 'rowIndex'
        let totalRow = { [numKey]: getLanCode() === 'zh' ? '合计' : 'Total' }
        //需要合计的列
        let parseCols =
          'initialStock,currentStock,currentStockPrice,initialAmount,thisMonthAmount,currentAmount,inSum,inSumPrice,inOutSumPrice,' +
          'outSum,outSumPrice,outInSumPrice,operNumber,allPrice,numSum,priceSum,prevSum,thisSum,thisAllPrice,changeAmount,' +
          'allPrice,currentNumber,lowSafeStock,highSafeStock,lowCritical,highCritical,preNeed,debtMoney,backMoney,allNeed' +
          'discountAllPrice,salesReturnPrice,discountLastMoney,taxMoney'+
          'checkAmount, totalPrice, notVerifiedAmount,receivedAmount,receivedAdvanceAmount,discountMoney' +
          'receivableAmount,discountLastMoney,straightDeposit,paid,unpaid,custom10,salesCost,salesGrossMargin,salesMargin,salesRevenue'+
          'outNumber,inNumber,outAllAmount,inAllAmount,netSales,taxLastMoney'
        columns.forEach(column => {
          let { key, dataIndex } = column
          if (![key, dataIndex].includes(numKey)) {
            let total = 0
            // 是否有原始customRender
            let falg = typeof(column.customRender) === 'function'
            dataSource.forEach((data,index) => {
              if (parseCols.indexOf(dataIndex) > -1) {
                // 是数字且没有自定义渲染，没有自定义返回函数
                if(!isNaN(data[dataIndex]) && typeof(column.customRender) !== 'function' && typeof(column.scopedSlots)==="undefined"){
                  column.customRender = (t,r,i)=>{
                    return sinceCount(t)
                  }
                }
                if (data[dataIndex]) {
                  total += Number.parseFloat(data[dataIndex])
                } else {
                  total += 0
                }
              } else {
                total = '-'
              }
            })
            if (total !== '-') {
              total = total.toFixed(2)
            }
            totalRow[dataIndex] = total
          }
        })
      if (dataSource.length > 0 && this.ipagination.pageSize % 10 === 1) {
        dataSource.push(totalRow)
        //总数要增加合计的行数，每页都有一行合计，所以总数要加上
        let size = Math.ceil(this.ipagination.total / (this.ipagination.pageSize - 1))
        this.ipagination.total = this.ipagination.total + size
      }
    },
    paginationChange (page, pageSize) {
      this.ipagination.current = page
      this.ipagination.pageSize = pageSize
      this.loadData(this.ipagination.current)
    },
    paginationShowSizeChange (current, size) {
      this.ipagination.current = current
      this.ipagination.pageSize = size
      this.loadData(this.ipagination.current)
    },
    getCurrentTiem(){
      let time = new Date()
      return time.getFullYear() + '-' + (time.getMonth()+1) +'-' +time.getDate()
    },
    
    loadTreeData() {
      let that = this;
      let params = {};
      params.id = '';
      queryMaterialCategoryTreeList(params).then((res) => {
        if (res) {
          that.categoryTree = [];
          for (let i = 0; i < res.length; i++) {
            let temp = res[i];
            that.categoryTree.push(temp);
          }
        }
      })
    },
    
    filterTreeNode(input,treeNode){
      return treeNode.data.props.title.toLowerCase().includes(input.toLowerCase())
    }, 
    reportPrint(){
      this.$refs.saleOutRepotModual.show()
    }
  }
}
